#include "stm8s_tim4.h"
#include "sys_pub.h"
volatile uint32_t system_ticks = 0;
volatile uint32_t system_time_ms=0;
uint32_t timestamp=0;
uint32_t run_time_sec=0;
uint16_t count_1000_tick=0;
/**
 * @brief  Initialize Timer2 (10ms interrupt)
 * @note   System clock is 16MHz, timer clock is 8MHz
 */
void sys_timer_init(void) {
    TIM4_TimeBaseInit(TIM4_PRESCALER_128,125);//初始化定时器4,1MS一次中断
    TIM4_ARRPreloadConfig(ENABLE);//使能自动重装
    TIM4_ITConfig(TIM4_IT_UPDATE , ENABLE);//数据更新中断
    TIM4_Cmd(ENABLE);//开定时器
}

/**
 * @brief  Timer2 interrupt handler
 */
void tick_handler(int system_ticks);
void sys_timer_upd()
{
    // Check update interrupt flag
    if (TIM4_GetITStatus(TIM4_IT_UPDATE) != RESET) {
        // 10ms callback processing
        system_ticks++;
        system_time_ms++;
        count_1000_tick++;
        if(count_1000_tick==1000)
        {
            count_1000_tick=0;
            run_time_sec++;
            timestamp++;
        }
        // Clear interrupt flag
        tick_handler(system_ticks);
        TIM4_ClearITPendingBit(TIM4_IT_UPDATE);
        
    }
}
 
uint32_t sys_get_tick_ms()
{
    return system_ticks;
}




// 获取系统时间 (毫秒)
uint32_t get_system_time_ms(void)
{
  return system_ticks;
}

// 获取系统时间 (秒)
uint32_t get_system_time_sec(void)
{
    return run_time_sec;
}
    